<?php
/**
 * passport api
 * @author zjx
 *
 */
class PassportApi {
	protected $httpclient;
	public static $urlPrefix = 'http://zjx.dld.com/passport';
	protected $content;
	public $tickets;
	protected $key;
	protected $appId;
	protected $prefixKey;
	public $statusCode;//请求返回状态码
	public function __construct($type = 'front') {
		$this->setApp ( $type );
	}
	/**
	 * 设置应用
	 * @param string $type
	 */
	public function setApp($type = 'front') {
		if ($type == 'front') {
			$this->appId = Yii::app ()->params ['frontpassportid'];
			$this->key = Yii::app ()->params ['frontpassportkey'];
			$this->prefixKey =WebUserD::PREFIX_KEY_FRONT;
		} else if($type=='admin'){
			$this->appId = Yii::app ()->params ['adminpassportid'];
			$this->key = Yii::app ()->params ['adminpassportkey'];
			$this->prefixKey =WebUserD::PREFIX_KEY_ADMIN;
		}else{
			throw new Exception('PsassportApi 实例化类型错误');
		}
	}
	/**
	 * @return the $appId
	 */
	public function getAppId() {
		return $this->appId;
	}
	/**
	 * 执行请求
	 * @param string $url
	 * @param array $params
	 */
	protected function excute($url, array $params = array()) {
		$this->httpclient = new HttpClientD ( $url );
		$this->httpclient->open ();
		//添加一个随机数，以防止出现重复提交现象
		$params['_rt']=microtime(true);
		foreach ( $params as $_k => $_v ) {
			$_v=UtilD::deSlashes($_v);
			$params [$_k] = XxteaD::encrypt ( $_v, $this->key );
		}
		
		$this->httpclient->setPostData ( $params );
		$this->content = $this->httpclient->excute ();
	}
	public function getContent() {
		return $this->content;
	}
	/**
	 * 获取请求内容
	 */
	public function getResponseData() {
		try {
			$result = UtilD::parseResult ( $this->content );
			$this->statusCode=$result['key'];
		} catch ( Exception $e ) {
			
			throw $e;
		}
		return $result;
	}
	/**
	 * 添加主帐号
	 * @param int $id
	 * @param int accounttype
	 * @param string $account
	 * @param string $pwd
	 */
	public function createAccount($accounttype = '', $account = '', $pwd = '') {
		$url = self::$urlPrefix . '/?r=user/add&id=' . $this->appId . '&accounttype=0';
		$params = array ("account" => $account, "pwd" => $pwd );
        $this->excute ( $url, $params );
        $result = $this->getResponseData ();
		return $result ['key'] == '1' ? true : false;
	}
	/**
	 * 添加子帐号
	 * @param int $accounttype 0 用户名（主帐号）, 1 邮箱, 2 手机， 3 QQ(open id)
	 * @param 主帐号 $account
	 * @param 子帐号 $subaccount
	 */
	public function createSubAccount($accounttype, $account, $subaccount){
		$url = self::$urlPrefix . '/?r=user/addChild&id=' . $this->appId . '&accounttype=' . $accounttype;
		$params = array ("account" => $account, "subaccount" => $subaccount);
		$this->excute ( $url, $params );
		$result = $this->getResponseData ();
		return $result ['key'] == '1' ? true : false;
	}
	/**
	 * 添加邮箱登录方式
	 * @param int $id
	 * @param string $account
	 * @param string $subaccount
	 */
	public function createEmailAccount($account = '',$subaccount='') {
		return $this->createSubAccount(1, $account, $subaccount);
	}
	/**
	 * 添加手机录方式
	 * $account 主帐号
	 * $subaccount 子帐号
	 */
	public function createMoblieAccount($account = '',$subaccount='') {
		return $this->createSubAccount(2, $account, $subaccount);
	}	
	
	/**
	 * 删除主帐号
	 * @param int $id
	 * @param int $accounttype
	 * @param string $account
	 * @param string $pwd
	 */
	public function removeAccount($account = '', $pwd = '') {
		$url = self::$urlPrefix . '/?r=user/delUser&id=' . $this->appId . '&accounttype=0';
		$params = array ("account" => $account, "pwd" => $pwd );
		$this->excute ( $url, $params );
		$result = $this->getResponseData ();
		return $result ['key'] == '1' ? true : false;
	}
	/**
	 * 删除子帐号
	 * @param int $accounttype
	 * @param string $account
	 */
	public function removeSubAccount( $accounttype, $account = '') {
		$url = self::$urlPrefix . '/?r=user/delChild&id='.$this->appId.'&accounttype=' . $accounttype;
		$params = array ("account" => $account);
		$this->excute ( $url, $params );
		$result = $this->getResponseData ();
		
		return $result ['key'] == '1' ? true : false;
	}
	/**
	 * 删除手机登录方式
	 * $account 子帐号
	 */
	public function removeMoblieAccount( $account = '') {
		return $this->removeSubAccount(2, $account);
	}
	/**
	 * 删除邮箱登录方式
	 * $account 子帐号
	 */
	public function removeEmailAccount( $account = '') {
		return $this->removeSubAccount(1, $account);
	}
	/**
	 * 帐号登录
	 * @param int $id
	 * @param int accounttype
	 * @param string $account
	 * @param string $pwd
	 */
	public function loginAccount($accounttype = '', $account = '', $pwd = '') {
		$currentIP = Yii::app ()->request->getUserHostAddress ();
		$url = self::$urlPrefix . '/?r=user/login&id=' . $this->appId . '&accounttype=' . $accounttype . '&currentIP=' . $currentIP;
		$params = array ("account" => $account, "pwd" => $pwd );
		$this->excute ( $url, $params );
		$result = $this->getResponseData ();
		if ($result ['key'] == '1') {
			$this->tickets = $result ['keyMain']['tickets'];
			return true;
		}
		return false;
	}
	/**
	 * 更改Email或者手机登录帐号
	 * @param int $id
	 * @param int accounttype
	 * @param string $account
	 * @param string $pwd
	 */
	public function updateAccount($accounttype = '', $account = '', $oldaccount = '') {
		if($accounttype!=1 && $accounttype!=2){
			return false;
		}
		$url = self::$urlPrefix . '/?r=user/repickAccount&id=' . $this->appId . '&accounttype=' . $accounttype;
		$params = array ("account" => $account, "oldaccount" => $oldaccount );
		$this->excute ( $url, $params );
		$result = $this->getResponseData ();
		return $result ['key'] == '1' ? true : false;
	}
	/**
	 * 根据主帐号重设密码
	 * @param int $id 1 后台 3 前台 
	 * @param int accounttype 登录类型(0 用户名, 1 邮箱, 2 手机)
	 * @param string $account 
	 * @param string $pwd
	 */
	public function resetPwd($accounttype = '', $account = '', $pwd = '') {
		$url = self::$urlPrefix . '/?r=user/resetPwd&id=' . $this->appId . '&accounttype=' . $accounttype;
		$params = array ("account" => $account, "pwd" => $pwd );
		$this->excute ( $url, $params );
		$result = $this->getResponseData ();
		return $result ['key'] == '1' ? true : false;
	}
	/**
	 * 检查帐号是否存在
	 * @param int $id
	 * @param int $accounttype 0 用户名, 1 邮箱，2 手机
	 * @param string $account
	 * @return boolean
	 */
	public function checkExists($accounttype = '', $account = '') {
		$url = self::$urlPrefix . '/?r=user/account&id=' . $this->appId . '&accounttype=' . $accounttype;
		$params = array ("account" => $account);
		$this->excute ( $url, $params );
		$result = $this->getResponseData ();
		if($result['key']=='1'){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 根据帐号获取用户数据
	 * @param int $id
	 * @param int $accounttype 0 用户名, 1 邮箱，2 手机, 3 qq
	 * @param string $account
	 * @return boolean
	 */
	public function getPassportCachedUserData($accounttype = 0, $account = '') {
		$url = self::$urlPrefix . '/?r=user/account&id=' . $this->appId . '&accounttype='.$accounttype;
		$params = array ("account" => $account );
		$this->excute ( $url, $params );
		$result = $this->getResponseData ();
		if($result['key']=='1'){
			$result_data = XxteaD::decrypt ( $result ['keyMain'], $this->key );
			$data = CJSON::decode ( $result_data );
			$data [WebUserD::STORAGE_KEY] = CJSON::decode ( $data [WebUserD::STORAGE_KEY] );
			return $data;
		}else{
			return false;
		}
	}
	/**
	根据令牌获取用户数据
	**/
	public function getPassportCachedUserDataByTickets($tickets,$accounttype=0){
			$url = self::$urlPrefix . '/?r=user/userAttributes&id=' . $this->appId.'&accounttype=0';
			$params = array ("tickets" => $tickets );
			$this->excute ( $url, $params );
			$result = $this->getResponseData ();
			if($result['key']=='1'){
				$result_data = XxteaD::decrypt ( $result ['keyMain'], $this->key );
				$data = CJSON::decode ( $result_data );
				$data [WebUserD::STORAGE_KEY] = CJSON::decode ( $data [WebUserD::STORAGE_KEY] );
				return $data;
			}else{
				return false;
			}
	}
	/**
	根据令牌设置用户数据
	**/
	public function setPassportCachedUserData($tickets,array $data,$accounttype = 0){
			if(!is_array($data) || count($data)<1){
				return false;
			}
            
			if(!isset($data['currentIP']) || $data['currentIP']==''){
				$data['currentIP']=Yii::app ()->request->getUserHostAddress ();
			}
			$url = self::$urlPrefix . '/?r=user/saveUserAttributes&id='. $this->appId.'&accounttype=0';
            $params = array ("tickets" => $tickets,'userattrubutes'=>CJSON::encode(array("{$this->prefixKey}"=>$data)));
            $this->excute ( $url, $params );
            $result = $this->getResponseData ();
			if ($result ['key'] == '1') {
				return true;
			}
			return false;

	}
	/**
	 * 根据用户缓存数据
	 * 
	 */
	public function setPassportCachedUserDataByName($username, array $data){
			if(!is_array($data) || count($data)<1){
				return false;
			}
			if(!isset($data['currentIP']) || $data['currentIP']==''){
				$data['currentIP']=Yii::app ()->request->getUserHostAddress ();
			}
            $url = self::$urlPrefix . '/?r=user/saveUserAttributesByAccount&id='. $this->appId.'&accounttype=0';
            $params = array ("account" => $username,'userattrubutes'=>CJSON::encode(array("{$this->prefixKey}"=>$data)));
            $this->excute ( $url, $params );
            $result = $this->getResponseData ();
			if ($result ['key'] == '1') {
				return true;
			}
			return false;
	}
	/**
	 * 强制生成并设置tickets
	 * @param unknown_type $account 主帐号
	 * @param unknown_type $cid 应用id
	 * @param unknown_type $accounttype 帐号类型
	 */
	public function setTickets($account='', $appId=0, $accounttype=0){
		$tickets=hash ( 'md5', $account.'^]'.$appId.'^]'.$accounttype );
		$this->tickets=$tickets;
	}
	/**
	 * 通过主帐号获取所有的子帐号
	 * @param string $account
	 * return array
	 */
	public function getSubAccountByMainAccount($account=''){
		$url = self::$urlPrefix . '/?r=user/getSubAccountByMainAccount&id=' . $this->appId . '&accounttype=0';
		$params = array ("account" => $account);
		$this->excute ( $url, $params );
		$result = $this->getResponseData ();
		if($result['key']=='1'){
			return CJSON::decode(XxteaD::decrypt ( $result ['keyMain'], $this->key ));
		}else{
			return array();
		}
	}
}

?>